package com.itheima.filter;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.filter
 ****/
@Component
public class AuthorizeFilter implements GlobalFilter,Ordered {

    @Autowired
    private RedissonClient redissonClient;

    /***
     * 过滤拦截
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取用户请求的地址
        String uri = exchange.getRequest().getURI().getPath();

        //判断地址在布隆过滤器中是否存在，如果不存在，则拒绝访问
        RBloomFilter<Object> bloomFilterArray = redissonClient.getBloomFilter("BloomFilterArray");
        if(!bloomFilterArray.contains(uri)){
            //拒绝用户请求
            exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }


    /***
     * 排序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }


    public static void main(String[] args) {
        System.out.println((Math.random()*10));
    }
}
